package de.idgard.android.service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import de.idgard.android.R;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.services.PropertiesService;
import de.idgard.android.proxy.IDGardProxyServer;

/**
 * 
 * @author ckaratza ALL SPAWNED THREADS SHOULD BE KILLED UPON APPLICATION EXIT!
 * 
 */

public class IDGardProxyService extends Service {
	@Override
	public void onCreate() {
		super.onCreate();
	}

	private ExecutorService executor;

	private void stopLocalProxy() {
		if (GlobalServiceRegistry.instance().getProxyService().getCommunicator() != null) {
			GlobalServiceRegistry.instance().getProxyService().getCommunicator().shutdownServer();
		}
		if (executor != null) {
			executor.shutdown();
		}
	}

	@Override
	public void onDestroy() {
		stopLocalProxy();
		super.onDestroy();
	}

	@Override
	public boolean stopService(Intent name) {
		stopLocalProxy();
		return super.stopService(name);
	}

	private PropertiesService getPropertiesService() {
		return GlobalServiceRegistry.instance().getPropertiesService();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		executor = Executors.newFixedThreadPool(10);
		int priorRunningPort = GlobalServiceRegistry.instance().getProxyService().getLastRunningPort();
		if (priorRunningPort == 0) {
			priorRunningPort = getPropertiesService().getInteger(R.string.base_local_proxy_incoming_port);
		}
		GlobalServiceRegistry
				.instance()
				.getProxyService()
				.setCommunicator(
						new IDGardProxyServer(getPropertiesService().getString(R.string.system_domain), getPropertiesService().getInteger(R.string.remotehttpsport),
								++priorRunningPort));
		GlobalServiceRegistry
				.instance()
				.getProxyService()
				.startLocalProxy("localhost", GlobalServiceRegistry.instance().getProxyService().getCommunicator().port,
						GlobalServiceRegistry.instance().getBrowserUtilityService().getIDGardData().getIdgardId(),
						GlobalServiceRegistry.instance().getBrowserUtilityService().getIDGardData().getJsessionId());
		executor.execute(GlobalServiceRegistry.instance().getProxyService().getCommunicator());
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
